<template>
  <div>
    <!-- 日期选择器 -->
    <div class="date-picker-container">
      <el-date-picker
        v-model="selectedDate"
        type="date"
        placeholder="选择日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
        @change="fetchData"
      />
    </div>

    <!-- 日收入情况 -->
    <h2>{{ chartTitles.dailyIncome }}</h2>
    <el-card shadow="hover">
      <!-- 删除:<p>日收入：<strong>{{ dailyIncomeData.totalIncome }}</strong></p> -->
      <div ref="incomeChartRef" style="width: 100%; height: 400px;"></div>
    </el-card>

    <!-- 菜品日销售情况 -->
    <h2>{{ chartTitles.dailyDishSales }}</h2>
    <el-card shadow="hover">
      <div ref="chartRef" style="width: 100%; height: 400px;"></div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue';
import * as echarts from 'echarts';
import axios from 'axios';
import { ElMessage } from "element-plus";
import { format, subDays } from 'date-fns';

// 获取当前店铺ID
const shopId = localStorage.getItem('shopInfo') ? JSON.parse(localStorage.getItem('shopInfo')).id : null;

// 响应式数据
const selectedDate = ref<string>(format(new Date(), 'yyyy-MM-dd')); // 默认当天
const dailyIncomeData = ref({ totalIncome: 0 });
const dishSalesData = ref<{ dishName: string; salesCount: number }[]>([]);
// 新增收入图表数据
const incomeChartData = ref<{ date: string; income: number }[]>([]);

// 图表标题
const chartTitles = {
  dailyIncome: '日收入情况',
  dailyDishSales: '菜品日销售情况'
};

// 图表容器引用
const chartRef = ref<HTMLElement | null>(null);
// 新增收入图表引用
const incomeChartRef = ref<HTMLElement | null>(null);

// 渲染菜品销售图表
const renderChart = () => {
  if (!chartRef.value) return;
  
  const chart = echarts.init(chartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%', // 增加底部空间防止标签被截断
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: dishSalesData.value.map(item => item.dishName),
      axisLabel: {
        interval: 0, // 显示所有标签
        rotate: 45 // 旋转标签防止重叠
      }
    },
    yAxis: {
      type: 'value',
      name: '销量'
    },
    series: [{
      name: '菜品销量',
      type: 'bar',
      data: dishSalesData.value.map(item => item.salesCount),
      itemStyle: {
        color: '#5470c6'
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  };
  
  chart.setOption(option);
  
  // 响应式调整图表大小
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

// 渲染收入图表
const renderIncomeChart = () => {
  if (!incomeChartRef.value) return;
  
  const chart = echarts.init(incomeChartRef.value);
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'shadow' }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: incomeChartData.value.map(item => item.date),
      axisLabel: {
        interval: 0,
        rotate: 45
      }
    },
    yAxis: {
      type: 'value',
      name: '收入 (元)'
    },
    series: [{
      name: '日收入',
      type: 'bar',
      data: incomeChartData.value.map(item => item.income),
      itemStyle: {
        color: '#f47b7b'
      },
      label: {
        show: true,
        position: 'top'
      }
    }]
  };
  
  chart.setOption(option);
  
  // 响应式调整图表大小
  window.addEventListener('resize', () => {
    chart.resize();
  });
};

// 获取数据
const fetchData = async () => {
  try {
    // 获取日收入
    const dailyIncomeResponse = await axios.get(`/api/income/daily-income/${shopId}?date=${selectedDate.value}`);
    
    // 获取菜品日销售数据
    const dishSalesResponse = await axios.get(`/api/income/daily-dish-sales/${shopId}?date=${selectedDate.value}`);
    
    // 处理日收入数据
    if (dailyIncomeResponse.data && dailyIncomeResponse.data.data !== undefined) {
      dailyIncomeData.value = {
        totalIncome: dailyIncomeResponse.data.data.totalIncome
      };
    } else {
      console.warn('Daily income data is empty or null');
      dailyIncomeData.value = { totalIncome: 0 };
    }
    
    // 处理菜品销售数据
    if (dishSalesResponse.data && dishSalesResponse.data.data) {
      dishSalesData.value = Object.entries(dishSalesResponse.data.data).map(([dishName, salesCount]) => ({
        dishName,
        salesCount: parseInt(salesCount)
      }));
    } else {
      console.warn('Dish sales data is empty or null');
      dishSalesData.value = [];
    }
    
    // 获取近10日收入数据
    await fetchIncomeChartData();
    
    // 在获取数据后，使用nextTick确保DOM更新后再渲染图表
    nextTick(() => {
      renderChart();
      renderIncomeChart();
    });
    
  } catch (error) {
    console.error('数据加载失败:', error);
  }
};

// 获取近10日收入数据
const fetchIncomeChartData = async () => {
  try {
    const dates = [];
    const today = new Date(selectedDate.value);
    
    // 生成过去10天到今天的日期
    for (let i = 10; i >= 0; i--) {
      const date = subDays(today, i);
      dates.push(format(date, 'yyyy-MM-dd'));
    }
    
    // 获取每日收入数据
    const incomePromises = dates.map(date => 
      axios.get(`/api/income/daily-income/${shopId}?date=${date}`)
    );
    
    const incomeResponses = await Promise.all(incomePromises);
    
    // 处理收入数据
    incomeChartData.value = dates.map((date, index) => {
      const response = incomeResponses[index];
      const income = response.data && response.data.data && response.data.data.totalIncome 
        ? response.data.data.totalIncome 
        : 0;
      return {
        date: format(new Date(date), 'MM-dd'),
        income: parseFloat(income.toFixed(2))
      };
    });
  } catch (error) {
    console.error('获取收入图表数据失败:', error);
    incomeChartData.value = [];
  }
};

// 组件挂载时获取数据
onMounted(async () => {
  await fetchData();
});
</script>

